package main

import (
	"bytes"
	"crypto/md5"
	"fmt"
	"io/ioutil"
	"net/http"
	"sort"
	"time"
)

func main()  {
	now := time.Now().UnixMilli()
	secret := "abc123"//需要跟服务端的key保持一致
	args := map[string]interface{}{
		"a":1,
		"name":"keo",
		"time": now,
		"key": 1,
	}
	keys := make([]string,0,len(args))
	for k,_ := range args{
		keys = append(keys, k)
	}
	sort.Strings(keys)
	var signchar bytes.Buffer
	for _,v := range keys{
		switch args[v].(type) {
		case string:
			signchar.WriteString(v)
			signchar.WriteString("=")
			signchar.WriteString(args[v].(string))
			signchar.WriteString("&")
		case int,int64:
			signchar.WriteString(v)
			signchar.WriteString("=")
			signchar.WriteString(fmt.Sprintf("%v",args[v]))
			signchar.WriteString("&")
		}
	}
	signchar.WriteString(secret)
	fmt.Println(signchar.String())
	sign := fmt.Sprintf("%x",md5.Sum(signchar.Bytes()))

	request, err := http.NewRequest("GET", "http://127.0.0.1/sign", nil)
	if err != nil {
		panic(err)
	}

	query := request.URL.Query()

	query.Add("sign", sign)
	for k,v := range args{
		query.Add(k, fmt.Sprintf("%v",v))
	}
	request.URL.RawQuery = query.Encode()

	//发送请求给服务端,实例化一个客户端
	client := &http.Client{}
	res, err := client.Do(request)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	//服务端返回数据
	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}
	fmt.Printf(string(b))
}